package com.zzyl.service.impl;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.google.common.collect.Sets;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.Dept;
import com.zzyl.entity.Post;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.*;
import com.zzyl.service.UserService;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import net.bytebuddy.implementation.bind.annotation.Super;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.*;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Autowired
    private DeptMapper deptMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PostMapper postMapper;


    /**
     * 添加
     * @param userDto
     */
    @Transactional
    @Override
    public void createUser(UserDto userDto) {

        //先判断是否是最底层部门
        if (confirmLowest(userDto.getDeptNo())) {
            throw new BaseException(BasicEnum.USER_LOCATED_BOTTOMED_DEPT);
        }


        User user = new User();
        BeanUtil.copyProperties(userDto, user);
        String password = "888itcast.CN764%...";
        user.setPassword(BCrypt.hashpw(password,BCrypt.gensalt()));
        user.setUsername(user.getEmail());
        user.setNickName(user.getRealName());
        user.setDataState(SuperConstant.DATA_STATE_0);
        userMapper.insert(user);

        //最后需要取出集合数据，对中间表进行添加
        List<UserRole> userRoles = new ArrayList<>();
        userDto.getRoleVoIds().forEach(r -> {
            userRoles.add(UserRole.builder().userId(user.getId())
                    .roleId(Long.valueOf(r)).dataState(SuperConstant.DATA_STATE_0).
                    build());
        });
        userRoleMapper.batchInsert(userRoles);
    }


    /**
     * 修改
     */
    @Override
    public void modify(UserDto userDto) {

        if (confirmLowest(userDto.getDeptNo())) {
            throw new BaseException(BasicEnum.USER_LOCATED_BOTTOMED_DEPT);
        }
        User user = new User();
        BeanUtil.copyProperties(userDto, user);
        userMapper.modify(user);

        List<UserRole> userRoles = new ArrayList<>();

        Set<String> roleVoIds = userDto.getRoleVoIds();
        if (roleVoIds != null) {
            userRoleMapper.deleteByUserId(user.getId());
            userDto.getRoleVoIds().forEach(r -> {

                userRoles.add(UserRole.builder().userId(user.getId())
                        .roleId(Long.valueOf(r)).dataState(SuperConstant.DATA_STATE_0).
                        build());
            });
            userRoleMapper.batchInsert(userRoles);
        }
    }

    /**
     * 启用禁用
     * @param id
     * @param status
     */

    @Override
    public void enableOrDisable(Long id, String status) {
        userMapper.enableOrDisable(id, status);

    }


    /**
     * 用户列表
     *
     * @param userDto
     * @return
     */
    @Override
    public List<UserVo> userList(UserDto userDto) {
        User user = new User();
        BeanUtil.copyProperties(userDto, user);
        List<UserVo> userVos = userMapper.userList(user);
        return userVos;
    }

    /**
     * 用户分页
     * @param userDto
     * @return
     */
    @Override
    public PageResponse<UserVo> findByPage(UserDto userDto, int pageNum, int pageSize) {

        PageHelper.startPage(pageNum, pageSize);
        Page<User> page = (Page<User>) userMapper.findByPage(userDto);
        PageResponse<UserVo> pageInfo = PageResponse.of(page, UserVo.class);

        List<UserVo> records = pageInfo.getRecords();

        if (records.isEmpty()) {
            return pageInfo; // 如果没有记录，直接返回
        }

        // 提取用户ID列表并转换为字符串
        List<Long> userIds = records.stream()
                .map(record -> record.getId()) // 假设getId()返回类型是Long或可以自动装箱为Long
                .collect(Collectors.toList());
// 查询对应角色（假设 roleMapper.findRoleVoListInUserId 方法返回的是 List<RoleVo>）
        List<RoleVo> roleVoList = roleMapper.findRoleVoListInUserId(userIds);
        records.forEach(n -> {
            Set<String> roleVoIds = new HashSet<>();
            Set<String> roleVoLabels = new HashSet<>();
            roleVoList.forEach(r -> {
                if (String.valueOf(n.getId()).equals(r.getUserId())) {
                    roleVoIds.add(String.valueOf(r.getId()));
                    roleVoLabels.add(r.getRoleName());
                }
            });
            n.setRoleVoIds(roleVoIds);
            n.setRoleLabels(roleVoLabels);

        });


       /* List<RoleVo> roleVoList = roleMapper.findRoleVoListInUserId(userIds);

        // 将 roleVoList 转换为 Map，键是 userId，值是该用户的角色信息列表
        Map<String, List<RoleVo>> roleVoMap = roleVoList.stream()
                .collect(Collectors.groupingBy(roleVo -> roleVo.getUserId())); // 使用 Lambda 表达式

        // 遍历 records
        records.forEach(n -> {
            Set<String> roleVoIds = new HashSet<>();
            Set<String> roleVoLabels = new HashSet<>();

            // 从 roleVoMap 中获取对应 userId 的角色信息
            String userId = String.valueOf(n.getId());
            List<RoleVo> roles = roleVoMap.getOrDefault(userId, Collections.emptyList());

            roles.forEach(r -> {
                roleVoIds.add(String.valueOf(r.getId()));
                roleVoLabels.add(r.getRoleName());
            });

            n.setRoleVoIds(roleVoIds);
            n.setRoleLabels(roleVoLabels);
            System.out.println(roleVoLabels);
        });*/
        return pageInfo;

    }


    /**
     * 删除用户
     *
     * @param userId
     */
    @Override
    public void deleteByUserId(String userId) {
        deptMapper.deleteByUserId(userId);
        userRoleMapper.deleteByUserId(Long.valueOf(userId));

    }


    /**
     * 密码重置
     *
     * @param userId
     */
    @Override
    public void resetPassword(String userId) {
        deptMapper.resetPassword(userId);

    }


    private boolean confirmLowest(String deptNo) {
        int count = deptMapper.confirmLowest(deptNo);
        if (count > 0) {
            return true;
        } else {
            return false;
        }
    }
}
